﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using FeedReader.Shared.Data;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
namespace FeedReader.Shared.Data
{
    //created to standardise the proicessing of blobnames throughout the lifecycle. 
    //we have one place to change things if we wish too. 
    public static class BlobNameServices
    {
        public static string generateBlobName(string url)
        {
            string hash = Utils.HashToBase64(url);
            string result =HttpUtility.UrlPathEncode(hash);
            return string.Format("{0}.xml", result.Replace("+","0"));
        }

        public static string CreateBlobEntry(string url, BlogIDDataSource source)
        {
            string name = generateBlobName(url);
            
            BlogIDDataModel newitem = new BlogIDDataModel();

            newitem.RSSURL = url;
            newitem.BlogID = name;
            newitem.DateTime = DateTime.Now;
            try
            {
                source.Insert(newitem);
            }
            catch (Exception ex)
            {

            }
            return name;
        }

        public static bool Exists(BlogIDDataSource source, string url)
        {
            List<BlogIDDataModel> results = (from d in source.Select()
                                            where d.RSSURL == url
                                            select d).ToList<BlogIDDataModel>();

            if (results.Count == 0)
            {
                return false;
            }

            return true;
        }

        public static string getBlobID(BlogIDDataSource source,string p)
        {
            List<BlogIDDataModel> results = (from d in source.Select()
                                             where d.RSSURL == p
                                             select d).ToList<BlogIDDataModel>();
            return results.ElementAt(0).BlogID;
        }
    }

}
